<?php

namespace app\backend\controller;

use think\Controller;
use think\Request;
use app\common\model\Business as businessModel;
use app\common\model\Shoptype as shoptypeModel;
use app\common\model\User as userModel;
use app\common\model\ShopConfig;
use app\common\model\WalletLog as walletLogModel;
use app\common\model\IntegralLog as integralLogModel;
use app\common\model\Money as moneyModel;
use app\common\model\Notice as NoticeModel;
use think\Db;
use think\Validate;
class Business extends Controller
{
    /**
     * 显示申请列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //入驻协议
        $protocol = Db::name('notice')->where('type', 0)->find();
        $this->assign('protocol', $protocol);
        return $this->fetch();
    }
    /**
     * 查询申请信息
     */
    public function businessList()
    {
        $limit = request()->param('limit', 18);
        $keyword = request()->param('keyword');
        $status = request()->param('status');
        $map = array();
        if($keyword){
            $map['userid'] = $keyword;
        }
        if($status){
            $new_status = intval($status) -1;
            $map['status'] = $new_status;
        }
        $business_list = businessModel::where($map)->where('name','<>','')->paginate($limit);
        if ($business_list) {
            $data = ['code' => 0, 'msg' => '申请列表', 'count' => $business_list->total(), 'data' => $business_list->items()];
            return json($data);
        } else {
            $data = ['code' => 0, 'msg' => '申请列表', 'count' => $business_list->total(), 'data' => array()];
            return json($data);
        }
    }
    /**
     * 商家详情
     */
    public function edit()
    {
        if (request()->isPost()) {
            $id = input('post.userid');
            //print_r($_POST);exit;
            $status = input('post.status');
            if($status == 1){
                $edit = businessModel::where('userid', $id)->update(['status'=>1]);
                userModel::where('id',$id)->update(['is_business'=>1]);//user表里的is_business
            }else{
                $info  = businessModel::where('userid', $id)->field('status')->find();
                //print_r($info);exit;
                //echo $info['status'];exit;
                if($info['status'] == '审核失败'){
                    $data = ['code' => 1, 'msg' => '编辑失败'];
                    return $data;
                }
                $edit = businessModel::where('userid', $id)->update(['status'=>2]);
                userModel::where('id',$id)->update(['is_business'=>0]);//user表里的is_business
                //审核失败 退回会员GMOB

                $cmoney =walletLogModel::where(['userid'=>$id,'type'=>28])->order('id desc')->find();
                $cintegral=integralLogModel::where(['userid'=>$id,'type'=>19])->order('id desc')->find();
                if(!$cmoney['id']){
                    $cmoney=ShopConfig::where(['id'=>4,'filed'=>'deduction_money'])->find();
                    $cmoney['money'] = $cmoney['num'];
                }
                if(!$cintegral['id']){
                    $cintegral=ShopConfig::where(['id'=>3,'filed'=>'deduction_integral'])->find();
                }
                //echo $cmoney['money']."++".$cintegral['num'];exit;
                $resultdata=moneyModel::where('uid',$id)->find();
                if($cmoney['id']){
                    moneyModel::where('uid',$id)->setInc('wallet_num',$cmoney['money']);
                    //生成记录
                    $datamoneylog=[
                        'userid' => $resultdata['uid'],
                        'money' => $cmoney['money'],
                        'type' => 29,
                        'before_wallet' => $resultdata['wallet_num'],
                        'now_wallet' => $resultdata['wallet_num']+$cmoney['money'],
                        'create_time'=>time()
                    ];
                    WalletLogModel::create($datamoneylog);
                }
                if($cintegral['id']) {
                    moneyModel::where('uid',$id)->setInc('integral_num', $cintegral['num']);
                    $dataintegrallog = [
                        'userid' => $resultdata['uid'],
                        'num' => $cintegral['num'],
                        'type' => 20,
                        'before_integral' => $resultdata['integral_num'],
                        'now_integral' => $resultdata['integral_num']+$cintegral['num'],
                        'create_time' => time()
                    ];
                    integralLogModel::create($dataintegrallog);
                }
            }

            if($edit){
                $data = ['code' => 0, 'msg' => '编辑成功'];
            }else{
                $data = ['code' => 1, 'msg' => '编辑失败'];
            }
            return $data;
        }else{
            $status = array(
                0=>'未审核',
                1=>'已审核',
                2=>'审核失败',
            );
            $typeInfo = shoptypeModel::order('sort asc')->field('typeid,type_name')->select();
            $id = input('get.id');
            $data = businessModel::where("userid",$id)->find();
            $data['orga_img'] = explode(",",$data['orga_img']);
            $this->assign('data', $data);
            $this->assign('status', $status);
            $this->assign('typeInfo', $typeInfo);
            return $this->fetch();
        }
    }
    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete()
    {
        $id = input('post.id');
        $admin = false;
        if($id){
            $admin = businessModel::where('userid',$id)->delete();
        }
        if($admin){
            userModel::where('id',$id)->update(['is_business'=>0]);//user表里的is_business
            $data = ['code' => 0, 'msg' => '删除成功'];
        }else{
            $data = ['code' => 1, 'msg' => '删除失败'];
        }
        return $data;
    }
    /**
     * 添加商城公告
     */
    public function addShopNotice()
    {
        if (request()->isPost()) {
            $info = input('post.');
            $info['type'] = 2;      //商城公告
            //导读限字
            $newStr = preg_replace('/[^\x{4e00}-\x{9fa5}]/u', '', $info['read']);
            $strlen=mb_strlen($newStr,"utf-8");//检测汉字的个数
            if($strlen>16){
                $this->error('导读请填写15字以内');
            }
            $add = NoticeModel::create($info);
            $this->success('公告添加成功');

        }
        return $this->fetch();
    }
    /**
     * 修改商城公告
     */
    public function editShopNotice()
    {
        if (request()->isPost()) {
            $info = input('post.');
            //导读限字
            $newStr = preg_replace('/[^\x{4e00}-\x{9fa5}]/u', '', $info['read']);
            $strlen=mb_strlen($newStr,"utf-8");//检测汉字的个数
            if($strlen>16){
                $this->error('导读请填写15字以内');
            }else{
                // $img_obj=request()->file();
                // if(isset($img_obj['titleFile'])){
                //     $file=$img_obj['titleFile'];
                //     $img = $file->validate(['size' => 2048000, 'ext' => 'jpg,png,gif'])->move('uploads');
                //     if ($img) {
                //         // 成功上传后 获取上传信息
                //         // 输出 42a79759f284b767dfcb2a0197904287.jpg
                //         $img_name = $img->getSaveName();
                //         $info['title_img']="/uploads/$img_name";
                //     } else {
                //         // 上传失败获取错误信息

                //         $img_name = $file->getError();
                //     }
                // }

                $edit = NoticeModel::update($info);
                $this->success('公告修改成功');

            }
        }
        $id = input('get.id');
        $notice = NoticeModel::get($id);
        $this->assign('notice', $notice);
        return $this->fetch();
    }

    /**
     * 入驻协议
     */
    public function editShopProtocol()
    {
        if (request()->isPost()) {
            $info = input('post.');
            $info['type'] = 0;
            if(!empty($info['id']))
            {
                $edit = NoticeModel::update($info);
                $this->success('修改成功');
            }else
            {
                $add = NoticeModel::create($info);
                $this->success('修改成功');
            }

        }
        $id = input('get.id');
        $notice = NoticeModel::get($id);
        $this->assign('notice', $notice);
        return $this->fetch('protocol', compact($id, $notice));
    }

    //行业新闻
    public function industryNotice()
    {
        $notice = NoticeModel::where('type', 3)->order('update_time desc')->select();
        $this->assign('notice', $notice);
        return $this->fetch();
    }
    /**
     * 内容图片
     */
    public function uploadImg()
    {
        $files = request()->file();
        foreach ($files as $file) {
            // 移动到框架应用根目录/uploads/ 目录下
            $info = $file->validate(['size' => 2048000, 'ext' => 'jpg,png,gif,jpeg'])->move('uploads');
            if ($info) {
                // 成功上传后 获取上传信息
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                $img_name = $info->getSaveName();
            } else {
                // 上传失败获取错误信息
                $img_name = $file->getError();
            }
        }

        $data = ['code' => 0, 'msg' => $img_name, 'data' => ['src' => "/uploads/$img_name"]];
        return json($data);

    }
}
